<?php 
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * 商品属性（一）
 */
class Value extends Auth_Controller{

    public function __construct(){
        parent::__construct();

        $this->load->model('value_mdl');
        $this->load->model('attribute_mdl','att_mdl');
        $this->load->model('goods_mdl');
    }

    /**
     * 商品属性列表
     * @return [type] [description]
     */
    public function update(){
        $gid = $this->input->get('gid',TRUE);

        if(empty($gid)){
            show_error('参数错误');
            exit;
        }

        //查询对应商品
        $this->db->where('id',$gid);
        $this->db->where('status !=',0);
        $this->db->select('id,sort_id,name');
        $goods_res = $this->goods_mdl->get_one();

        if(empty($goods_res)){
            show_error('参数错误1');
        }

        //查询对应分类属性
        $this->db->select('id,aname,avalue,pid,describe');
        $this->db->where('sort_id',$goods_res['sort_id']);
        $att_list = $this->att_mdl->select();
        $att_res = $this->att_mdl->get_list($att_list);

        //加入商品属性表中
        $list_value = $this->value_mdl->create($att_res,$gid);

        $data = [
            'att_list' => $att_res,
            'val_list' => $list_value,
            'gid' => $gid
        ];
        $this->_view('admin/value_updata',$data);
    }


    public function editvalue(){
        if(!$this->input->is_ajax_request()){
            show_404();
            exit;
        }

        $post = $this->input->post(NULL,TRUE);

        if(empty($post)){
            die(1);
        }

        //检测
        foreach($post['value'] as $k => $v){
            $value = trim($v);
            if(empty($value)){
                die("所有选项都不能为空");
            }
        }

        $tmp = 0;

        $this->db->trans_start();
        foreach($post['value'] as $k => $v){
            $this->db->where('id',$k);
            $res = $this->value_mdl->update(['value'=>$v]);
            if($res === false){
                $tmp += 1;
            }
        }
        $this->db->trans_complete();

        echo $tmp === 0 ? 1 : '添加商品属性失败！';


    }

}